var db = require('../../db/db');
var publictool = require("../../publictool/publictool");

exports.port = function (req, res) {
    var requestData = '';
    req.addListener('data', function (postDataChunk) {
        requestData += postDataChunk;
    });

    req.addListener('end', function () {
        publictool.putlog(req, requestData);
        var phone = publictool.checkoutdata(res, requestData);
        if (!phone) {
            return;
        }

        var client = db.client();
        db.checkuser(client, res, false, phone.accesstoken)
            .then(function (resultvalue) {
                var sql = 'SELECT * FROM productInfo';
                var addSqlParams = [];
                if (phone.bundleId) {
                    sql = 'SELECT * FROM productInfo where bundleid=?';
                    addSqlParams = [phone.bundleId];
                }

                client.query(sql, addSqlParams, function (err, result) {
                    if (err) {
                        publictool.returnErr(res, '查询参数错误' + '[SELECT ERROR] - ' + err.message, 1);
                        client.end();
                        return;
                    }

                    var value = processresult(result);

                    publictool.returnValue(res, value, '成功');
                    client.end();
                    return;
                });
            });
    });
};

function processresult(result) {
    var value = {
        data: result
    };

    if (!result.length) {
        return value;
    }

    var bundlearr = [];
    for(var i = 0; i < result.length; ++i){
        var resultvalue = result[i];
        if(bundlearr.indexOf(resultvalue.bundleid) == -1){
            bundlearr.push(resultvalue.bundleid);
        }
    }

    var resultarr = [];
    for(var i = 0; i < bundlearr.length;++i){
        var key = bundlearr[i];
        var resultv = {};
        resultv[key] = [];
        resultarr.push(resultv);
    }

    for(var i = 0; i < result.length;++i){
        var resultvalue = result[i];
        var key = resultvalue.bundleid;
        var index = bundlearr.indexOf(key);
        if (index == -1){
            break;
        }
        var addvalue = {
            "prodcunt_id":resultvalue.productid,
            "price":resultvalue.price,
            "desc":resultvalue.des
        }
        var data = resultarr[index];
        if(!data){
            break;
        }
        var key = resultvalue.bundleid;
        var arr = data[key];
        arr.push(addvalue);
    }

    value.data = resultarr;

    return value;
}